package com.xm.xmds1705083.service.netty;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletException;
import java.nio.charset.Charset;

/**
 * @Company 杭州新苗网络科技有限公司
 * @Author : loysen
 * @DateTime：2017年4月22日 下午5:54:15
 *
 * @Description : {Netty初始化类}
 */
@Service
public class DeviceTCPServerInitializer extends ChannelInitializer<SocketChannel> {

	@Autowired
	private DeviceTCPServerHandler deviceTCPServerHandler;

	Logger logger = LoggerFactory.getLogger(DeviceTCPServerInitializer.class );

	private DispatcherServlet dispatcherServlet;

	public DeviceTCPServerInitializer() throws ServletException{

		logger.info("√×§♬♫♪♩★★★★★★xmds1705083-service-provider服务启动成功★★★★★★");
		System.out.println("§♬♫♪♩★★★★★★xmds1705083-service-provider服务启动成功★★★★★★");

	}

	@Override
	public void initChannel(SocketChannel ch) {
		logger.info("server-channel初始化--------------------------> ");

		ChannelPipeline pipeline = ch.pipeline();
		// Add the number codec first,
		// 解析
		pipeline.addLast(new ServerSocketEntityDecoder());
		pipeline.addLast(new ServerSocketEntityEncoder());
		pipeline.addLast("logging",new LoggingHandler(LogLevel.DEBUG));



		// 3 minutes for read idle
		// 心跳机制
		ch.pipeline().addLast("IdleHandler", new IdleStateHandler(30, 30, 30));
		// -- 自定义心跳解析

		ch.pipeline().addLast("MyIdleHandler", new MyIdleHandler());

		/*pipeline.addLast("StringDecoder", new StringDecoder(Charset.forName("UTF-8")));
		pipeline.addLast("StringEncoder", new StringEncoder(Charset.forName("UTF-8")));*/


		// and then business logic.
		// Please note we create a handler for every new channel
		// because it has stateful properties.
		pipeline.addLast(deviceTCPServerHandler);
	}
}
